package org.carabiner.infinitest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import junit.framework.TestCase;

public class TestExternalProcessTestRunner extends TestCase implements TestStatusListener
{
  private static File LOCK_FILE = new File("runner.lck");
  private static final String MESSAGE = "message";
  private List<TestEvent> events;
  
  protected void setUp() throws Exception
  {
    super.setUp();
    events = new ArrayList<TestEvent>();
    LOCK_FILE.delete();    
  }
    
  protected void tearDown() throws Exception
  {
    LOCK_FILE.delete();
    events = null;
  }
  
  public void testRunTest() throws Exception
  {
    ExternalProcessTestRunner runner = new ExternalProcessTestRunner(StubTestRunner.class);
    runner.addTestStatusListener(this);
    runner.runTest(TestExternalProcessTestRunner.class.getName());    
    assertTrue(LOCK_FILE.exists());
    assertTrue(LOCK_FILE.delete());
    assertEquals(1, events.size());
    TestEvent testEvent = events.get(0);
    assertNull(testEvent.getSource());
    assertEquals(TestExternalProcessTestRunner.class.getName(), testEvent.getTestName());
    assertEquals(MESSAGE, testEvent.getMessage());
    assertEquals("testMethod", testEvent.getTestMethod());
  }
  
  public static class StubTestRunner implements TestRunner
  {    
    private static final String TEST_METHOD = "testMethod";
    private TestStatusListener listener;
    
    public void addTestStatusListener(TestStatusListener statusListener)
    {      
      listener = statusListener;
    }

    public void runTest(String testClass)
    {
      try
      {
        assertTrue(LOCK_FILE.createNewFile());
      }
      catch (IOException e)
      {
        throw new RuntimeException(e);
      }      
      listener.testMethodSucceeded(new TestEvent(this, MESSAGE, testClass, TEST_METHOD, null ));
    }    
  }

  public void testCaseSucceeded(TestEvent event)
  {
    events.add(event);    
  }

  public void testError(TestEvent event)
  {
    events.add(event);    
  }

  public void testFailed(TestEvent event)
  {
    events.add(event);    
  }

  public void testMethodSucceeded(TestEvent event)
  {
    events.add(event);    
  }  
}
